<!-- 书本详情 -->
<template>
    <div class="book-detail-box" @scroll="scrollLoad()" ref="review">
        <div class="task-history" v-if="hasHistory" @click="goHistory()">查看历史数据</div>
        <div :class="{'book-detail-bg':state==1}">
            <div :class="['book-detail',{'has-task-box':state==1}]">
                <!-- 没有任务 -->
                <div class="no-task" v-if="state==0">
                    <div class="book clearfix">
                        <img class="book-img shadow1 left" :src="book.bookCover" alt="">
                        <div class="book-info left">
                            <h3>{{book.bookName}}</h3>
                            <div class="author">{{book.bookCountry}} · {{book.bookAuthor}}</div>
                            <p>{{book.bookPress}}</p>
                            <p>{{book.wordNumber}}字</p>
                            <div class="label clearfix">
                                <span>{{book.gradeName}}</span>
                                <span v-show="book.awards">{{book.awards}}</span>
                            </div>
                        </div>
                    </div>
                    <!-- 任务数据 -->
                    <div class="task-data clearfix">
                        <ul class="left">
                            <li class="left" v-for="(item,index) in avatarList" :key="index">
                                <img :src="item" alt="">
                            </li>
                            <li class="left more"></li>
                        </ul>
                        <span>已有 <i>{{taskNum}}</i> 人创建任务 </span>
                    </div>
                    <!-- 简介 -->
                    <div class="book-intro" v-if="book.bookDescribe">
                        <div class="module-title">简介</div>
                        <div class="intro-box">
                            <p :class="{'is-ellipsis':isEllipsis}">{{book.bookDescribe}}</p>
                            <div :class="['btn-more',{'btn-less':!isEllipsis}]" @click="isEllipsis=!isEllipsis">{{introBtnTip}}</div>
                        </div>
                    </div>
                </div>
                <!-- 有任务 -->
                <div class="has-task" v-if="state==1">
                    <div class="book-box">
                        <div class="book-img shadow1">
                            <img :src="book.bookCover" alt="">
                            <span class="label">打卡中</span>
                        </div> 
                        <div class="book-title">{{book.bookName}}</div>
                        <div class="book-author">{{book.bookCountry}} · {{book.bookAuthor}}</div>
                    </div> 
                    <!-- 进度 -->
                    <div class="progress-box" v-if="type==0">
                        <div class="close-task"><span @click="closeTask()" v-if="task.userId==userid">终止打卡</span></div>
                        <div class="prog-time clearfix">
                            <span class="left"><span v-if="task.takeMinute==0">今日已读：</span><i>{{clockTime}}</i><span v-if="task.takeMinute">/{{task.takeMinute}}</span>分钟</span>
                            <em class="right">{{task.dayCount}}天阅读计划的第{{countday}}天</em>
                        </div>
                        <div class="in-progress" ref="in-progress" v-if="task.takeMinute">
                            <div class="in-elapse" ref="in-elapse" :style="'width:'+ inElapseP +'%;'"></div>
                        </div>
                    </div>
                    <div class="progress-box" v-if="type==1">
                        <div class="prog-time clearfix">
                            <span class="left"><i>{{countday}}天</i>/{{task.dayCount}}天阅读计划</span>
                            <em class="close-task right" @click="closeTask()" v-if="task.userId==userid">终止打卡</em>
                        </div>
                        <div class="in-progress" ref="in-progress">
                            <div class="in-elapse" ref="in-elapse" :style="'width:'+ inElapsePDay +'%;'"></div>
                        </div>
                        <div class="task-class">{{task.ClassName}}</div>
                    </div>
                </div>
                <!-- 书评 -->
                <div class="review-box" ref="review">
                    <div class="btn-writing" v-if="state==1 && type==0" @click="goWriting()">发表书评</div>
                    <div class="module-title">热门书评</div>
                    <ul class="review-list">
                        <li v-for="(item,index) in reviewList" :key="index">
                            <div class="li-top clearfix">
                                <img :src="item.avatar ? item.avatar : $parent.headError" alt="" :onerror="$parent.headError" class="left">
                                <i class="left">{{item.trueName}}</i>
                                <span class="right" v-show="item.userId==$parent.myInfo.UserId" @click="deleClick(item,index)">删除</span>
                            </div>
                            <div class="li-main" @click="goReview(item)"> 
                                <p>{{item.experienceContent}}</p>
                            </div>
                            <div class="li-bottom clearfix">
                                <i class="left">{{item.createTime}}</i>
                                <span class="left">{{item.pageInterval}}</span>
                                <div :class="[item.isPraise ? 'islike like right' : 'like right']" @click="likeClick(item)">{{item.praiseCount}}</div>
                            </div>
                        </li>
                    </ul>
                    <!-- 空状态 -->
                    <transition name='fade'>
                        <div class="no-con small" v-show="noConShow">
                            <img src="@/assets/img/no-con.png" alt="">
                            <p>暂无书评...</p>
                        </div>
                    </transition> 
                    <!-- 加载提示 -->
                    <div class="bottom-tips">{{bottomTip}}</div> 
                </div>
                
            </div>
        </div>
        <!-- 按钮 -->
        <div class="btn-box-main">
            <div class="btn-task clearfix" v-if="state==0">
                <div :class="['left btn-collect',{'is-collect':isCollect}]" @click="addBook()">{{isCollect ? '已加入书架':'加入书架'}}</div>
                <!-- <div class="left btn-read" v-if="chapterCon"  @click="goTryRead()">在线试读</div> -->
                <div class="left btn-read" @click="goTryRead()" v-if="canRead">在线阅读</div>
                <template v-if="canRead">
                    <router-link :to="{path:'/createTask',query: {bookid:bookid}}"><span :class="['right shadow2',{'has-read':chapterCon}]">创建打卡任务</span></router-link>
                </template>
                <template v-if="!canRead">
                    <router-link :to="{path:'/createTask',query: {bookid:bookid}}"><span :class="['right1 right shadow2',{'has-read':chapterCon}]">创建打卡任务</span></router-link>
                </template>
               
            </div>
            <div class="btn-clock clearfix" v-if="state==1 && type==0">
                <div class="left btn-challenge"  @click="goChallenge(task.taskId)">开始挑战</div>
                <div class="left btn-read" @click="goTryRead()" v-if="canRead">在线阅读</div>
                <span class="right shadow2" @click="goClock()">开始打卡</span>
            </div>
            <div class="btn-blue shadow2" v-if="state==1 && type==1" @click="goReport()">查看班级统计</div>
        </div>
        <!-- 提示弹窗 -->
        <Popup v-show="popupShow" :popupShow="popupShow" :popupType="2" :popupText="popupText" :popupTips="type==1 ? '所有学生的打卡任务都会终止':''" @popupCancel="popupCancel" @popupSure="popupSure"></Popup>
    </div>
</template>

<script>
import Popup from '@/components/Popup'
import { axGet } from '@/api/index'
import { setTimeout } from 'timers';

export default {
    name: "bookDetail",
    components:{
        Popup,
    },
    data(){
        return{
            type:this.$parent.myInfo.UserType,//0学生，1教师
            userid:this.$parent.myInfo.UserId,
            bookid:this.$route.query.bookid,  //书本id
            hasHistory:false,
            historyList:[],  //历史任务列表
            book:{},        //书本对象
            chapterCon:'',  //试读内容
            avatarList:[],  //头像列表
            taskNum:0,      //任务创建人数
            state:0,        //是否有创建任务
            task:{},        //任务对象
            countday:0,     //第几天
            clockTime:0,    //打卡完成时间
            inElapseP:0,    //进度条打卡时间
            inElapsePDay:0, //进度条天数
            introBtnTip:'展开全文',
            isEllipsis:true, //简介是否省略
            reviewList:[],   //书评列表
            isCollect:false, //是否加入过书架
            hasTryRead:false, //是否可试读
            // 提示弹窗
            popupShow:false,
            popupText:'确定要提前终止打卡任务吗？',
            // popupTips:this.type==1 ? '所有学生的打卡任务都会终止':'',
            // 分页
            noConShow:false,
            listPage:1,
            totalPage:1,
            bottomTip:'',
            isLoading:true,
            canRead:true
            
            
        }
    },
    watch:{
        isEllipsis(newVal,oldVal){
            if(newVal){
                this.introBtnTip='展开全文'
            }else{
                this.introBtnTip='收起全文'
            }
        },
    },
    created(){
        this.$parent.menuShow=false;
        this.$parent.scoreShow=false;
        touchTrue()
        /****** 验证登录 *****/ 
        if(!sessionStorage.getItem("myInfo")){
            this.$router.replace({path:'/',query: {}});
        }else{
            this.book = JSON.parse(sessionStorage.getItem("thisBook")) 
          
            this.getContentBook()
            this.getTaskInfo()
            this.getReview(1)
            this.getTaskData() 
            this.getHistory()
        }
        
    },
    mounted(){
       
    },
    destroyed(){
        touchTrue()
    },
    methods:{
        //获取书本内容
        async getContentBook(){
             let res = await axGet('GetBookReadingContent', {userId:this.userid,bookId:this.bookid,pageIndex:1})
             if(res.ResultCode === -1){
                 this.canRead =false
             }
             console.log('res',res)
        },
        // 去历史记录
        goHistory(){
            let taskFinish=localStorage.getItem("taskFinish"+this.task.taskId) ? localStorage.getItem("taskFinish"+this.task.taskId) : 0
            if(this.type==0 && this.state==1 && this.countday==this.task.dayCount && taskFinish==1){      //学生最后一天已经完成过打卡
                this.$router.push({path:'/history',query: {bookid:this.bookid,isLast:1}});
            }else if(this.type==0 && this.historyList[0].taskCategory==2){    //学生考试任务  
                this.$router.push({path:'/challengeEnd',query: {bookid:this.bookid,hastest:1,taskid:this.historyList[0].taskId,from:'history'}}); 
                // this.goChallenge(this.historyList[0].taskId)
            }else if(this.type==1 && this.historyList[0].taskCategory==2){ //教师最近记录是考试任务
                // sessionStorage.setItem("historyTest",JSON.stringify(this.historyList[0]))
                this.$router.push({path:'/testState',query: {bookid:this.bookid, from:'test', index:0}});
            }else{
                this.$router.push({path:'/history',query: {bookid:this.bookid}});
            }
        },
        // 去写书评
        goWriting(){
            this.$router.push({path:'/writing',query: {bookid:this.bookid}});
        },
        // 去书评详情
        goReview(item){
            sessionStorage.setItem("thisReview",JSON.stringify(item))
            this.$router.push({path:'/review',query: {bookid:this.bookid,reviewid:item.experienceId}});
        },
        // 试读
        goTryRead(){
            // this.$router.push({path:'/readOnLine',query: {bookid:this.bookid}});
            this.$router.push({path:'/readview',query: {bookid:this.bookid}});
            
        },
        //去打卡
        goClock(){
            if(this.task){
                sessionStorage.setItem("thisTask",JSON.stringify(this.task))
                this.$router.push({path:'/clock',query: {countday:this.countday,bookid:this.bookid}});
            }else{
                this.$LayerTip({
                    content:"数据准备中，请稍后再试",
                    time:1000,
                });
            }
        },
        //班级统计
        goReport(){
            if(this.task){
                sessionStorage.setItem("thisTask",JSON.stringify(this.task))
                this.$router.push({path:'/report',query: {bookid:this.bookid}});
            }else{
                this.$LayerTip({
                    content:"数据准备中，请稍后再试",
                    time:1000,
                });
            }
        },
        // 去挑战
        goChallenge(taskid) {
            axGet('GetBookQuestionAnswerLog', {
                userId:this.userid,
                bookId:this.bookid,
                taskid:taskid,
            }).then(res => {
                if(res.ResultCode === 1) {
                    if(res.Value && res.Value.lastAnswerRecord){//有挑战记录
                        sessionStorage.setItem("questionList",res.Value.lastAnswerRecord)
					    this.$router.push({path:'/challengeEnd',query: {bookid:this.bookid,rightcount:res.Value.rightCount}}); 
                    }else{
                        this.$router.push({path:'/challengeStart',query: {bookid:this.bookid}});
                    }
                }
            })
        },
        // 请求历史任务
        getHistory(){
            axGet('GetBookHistoryCheckInTask', {
                userId:this.userid,
                bookId:this.bookid,
            }).then(res => {
                if(res.ResultCode==1){
                    if (res.Value.length>0) {
                        sessionStorage.setItem("historyList",JSON.stringify(res.Value))
                        this.historyList=res.Value
                        this.hasHistory=true
                    }else{
                        this.hasHistory=false
                    }
                }
            }) 
        },
        // 请求任务信息
        getTaskInfo(){
            axGet('GetBookCheckInTask', {
                userId:this.userid,
                bookid:this.bookid,
            }).then(res => {
                if(res.ResultCode==1){
                    if(res.Value && res.Value.taskState==1 && res.Value.taskCategory!=2){
                        this.state=1
                        this.task=res.Value
                        this.getTaskTime()
                        let time=this.task.createTime.slice(0,10)
                        this.getCountDown(time)
                        this.inElapsePDay=this.countday>this.task.dayCount ? 100 : this.countday/this.task.dayCount*100;
                        // if(this.type==1){//教师端最后一天跳转
                        //     setTimeout(()=>{
                        //         let taskFinish=localStorage.getItem("taskFinish"+this.task.taskId)
                        //         if(this.countday==this.task.dayCount && taskFinish==0){
                        //             this.$router.push({path:'/history',query: {bookid:this.bookid,isLast:1}});
                        //             localStorage.setItem("taskFinish"+this.bookid,1)
                        //         }    
                        //     },1000)
                        // }
                    }else if(res.Value && res.Value.taskCategory==2 && this.type==1){
                        this.$router.replace({path:'/testState',query: {bookid:this.bookid}});
                    }else{
                        this.state=0
                    }
                    
                }
            })
        },
        getTaskTime(){
            axGet('GetTaskLogMinute', {
                userId:this.userid,
                TaskId:this.task.taskId,
            }).then(res => {
                if(res.ResultCode==1){
                    this.clockTime=Math.floor(res.Value%3600/60);
                    this.inElapseP=this.clockTime>this.task.takeMinute ? 100 : this.clockTime/this.task.takeMinute*100;
                }
            })
        },
        //获取任务打卡人数、是否在书架
        getTaskData(){
            axGet('GetHRBookExtInfo', {
                UserId:this.userid,
                BookId:this.bookid,
            }).then(res => {
                if(res.ResultCode==1){
                    this.avatarList = res.Value.AvatarList ? res.Value.AvatarList.slice(0,5) : []
                    this.taskNum = res.Value.Count
                    this.isCollect = res.Value.IsInMyBook
                    this.chapterCon = res.Value.TrialReadingContent
                    sessionStorage.setItem("chapterCon",JSON.stringify(this.chapterCon))
                    
                }
            })
        },
        //请求书评列表
        getReview(page){
            axGet('GetExperienceList', {
                userid:this.userid,
                bookid: this.bookid,
                PageIndex: page,
                PageSize:10,
            }).then(res => {
                if(res.ResultCode==1){
                    let listJson=res.Value.list;
                    listJson.forEach((item,i)=>{ 
                        this.reviewList.push(item)
                    })
                    if(page==1){
                        this.totalPage=res.Value.pageCount
                        this.reviewList.length==0 ? this.noConShow=true : this.noConShow=false
                    }
                    if(page<this.totalPage){
                        this.bottomTip='上拉加载更多'
                    }else{
                        this.bottomTip=''
                    }
                    this.isLoading=true;
                }else{
                    this.isLoading=false; 
                }
            })
        },
       
        // 添加书架
        addBook(){
            if(!this.isCollect){
                axGet('AddMyHRBook', {
                    bookid: this.bookid,
                    userId: this.userid,
                }).then(res => {
                    if(res.ResultCode==1){
                        this.isCollect=true;
                        this.$LayerTip({
                            content:"已加入书架",
                            time:1500,
                        });
                    }
                })
            }
        },
        // 关闭任务
        closeTask(){
            this.popupShow=true;
        },
        popupCancel(){
            this.popupShow=false;
        },
        popupSure(){
            axGet('StopTask', {
                UserId:this.userid,
                TaskId:this.task.taskId,
            }).then(res => {
                if(res.ResultCode==1){
                    this.popupShow=false;
                    this.state=0;
                }
            })
        },
        // 删除
        deleClick(item,index){
            axGet('DeleteExperience', {
                UserId:this.userid,
                ExperienceId: item.experienceId,
            }).then(res => {
                if(res.ResultCode==1 && res.Value){
                    this.$LayerTip({
                        content:"删除成功",
                        time:1000,
                    });
                    this.reviewList.splice(index,1)
                }
            })
        },
        // 点赞
        likeClick(item){
            if(item.isPraise){
                this.removePraised(item)
            }else{
                this.addPraised(item)
            }
        },
        addPraised(item){
            axGet('PostPraise', {
                FromUserId: this.userid,
                ToUserId:item.userId,
                PraiseCategory:0,
                PraiseIdentity:item.experienceId, 
            }).then(res => {
                if(res.ResultCode==1){
                    item.isPraise=true;
                    item.praiseCount=parseInt(item.praiseCount)+1; 
                }
            })
        },
        removePraised(item){//取消赞
            axGet('CancelPraise', {
                FromUserId: this.userid,
                ToUserId:item.userId,
                PraiseCategory:0,
                PraiseIdentity:item.experienceId, 
            }).then(res => {
                if(res.ResultCode==1){
                    item.isPraise=false;
                    item.praiseCount=parseInt(item.praiseCount)-1; 
                }
            })
        },
        getCountDown (time) {
            let countday = new Date().getTime() - new Date(time).getTime()
            this.countday = Math.ceil(countday / 1000 / 60 / 60 / 24)
        },
        // 滚动加载   
        scrollLoad(){
            let bodyH = this.$refs['review'].clientHeight;
            let scrollH = this.$refs['review'].scrollTop;
            let listH = this.$refs['review'].scrollHeight;
            // console.log(bodyH,scrollH,listH)
            if(scrollH+bodyH+100>listH && this.isLoading){
                this.isLoading=false
                this.bottomTip='努力加载中...'
                // console.log(this.totalPage)
                this.listPage=this.listPage+1;
                if(this.listPage<this.totalPage || this.listPage == this.totalPage){
                    let page=this.listPage;
                    this.getReview(page)
                }else{
                    if(this.reviewList.length>0){
                        this.bottomTip='到达世界的边缘咯...'
                        console.log('没有更多数据')
                    }else{
                        this.bottomTip=''; 
                    } 
                }
            }
        },
    }
}
</script>
<style type="text/css" scoped>
.task-history{
    height: 1rem;
    line-height: 1rem;
    font-size: 0.32rem;
    background: #f7f7f7 url(~@/assets/img/icon/arrow-r-n.png) no-repeat center right 0.32rem;
    background-size: 0.16rem auto;
    padding-left: 0.32rem;
}
.book-detail-box{
    width: 100%;
    height: 100%;
    overflow: scroll;
}
.btn-box-main .btn-task .right, .btn-box-main .btn-clock .right{
    width: 45%;
}
.btn-box-main .btn-task .right1, .btn-box-main .btn-clock .right1{
    width: 65%;
}
.has-task .label{
    width: 1.3rem;
    padding: 0.1rem 0;
    position: absolute;
    top: 0;
    left: 0;
    color: #fff;
    font-size: 0.26rem;
    text-align: center;
    border-radius:0.2rem 0 0.38rem 0; 
    background: #85cd0d;
}
.close-task{
    color: #02affe;
    text-align: right;
    font-size: 0.26rem;
    padding-bottom: 0.08rem;
}
</style>